import json
from apps.merchant.item.dao import ItemDao
from apps.user.dao import UserDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from decimal import Decimal
from apps.system.lessee.dao import LesseeDao

from apps.pay.order.countAward.countProfit import countProfitFun
from apps.merchant.coupon.dao import CouponDao
from apps.pay.order.dao import OrderDao
from apps.merchant.shop.dao import ShopDao

def countPersonalAwardHandle(order):
    _order = OrderDao().findOneByObjId(order.id)
    print('发放个个人奖励', order.content)
    content = json.loads(_order.content)
     # 购买者贡献点
    sendContributionValues = 0
    # 上级贡献点
    verticalSendContributionValues = 0
    # 商家贡献点
    shopSendContributionValueData = {}
    # 赠送购买者锁定积分
    selfSendIncomesLockeds = 0
    # 赠送加盟店锁定积分
    shopSendIncomesLockedData = {}
    # 加盟店结算金额
    shop_balanceData = {}
    # 直推购物积分
    verticalSendIncomes = 0
    # 商户推荐人奖励
    shopParentAwardData = {}
    # 日释放池
    freePoolDays = 0
    # 月释放池
    freePoolMonths = 0
    # 运营补贴
    operationAwards = 0
    # 供应链奖励
    supplyAwards = 0
    # 创业基金
    helpFunds = 0
    # 毛利润
    grossProfits = 0
    # 如果用户有立减券
    if content.get('coupon'):
        _coupon = CouponDao().findOneByObjId(content.get('coupon'))
        if _coupon:
            sellingPrice = _order.sellingPrice - _coupon.fullMoney
            costPrice = (sellingPrice / _order.sellingPrice) * _order.costPrice
            CouponDao().update(_coupon.id, {'status': 'has_use'})
        else:
            sellingPrice = _order.sellingPrice
            costPrice = _order.costPrices
        orderItem = countProfitFun({'sellingPrice': sellingPrice, 'costPrice': costPrice, 'activityId': 30, 'scene': 'generay'})
        orderItem['payCount'] = 1
        sendContributionValues = sendContributionValues + Decimal(orderItem.get('sendContributionValue'))*Decimal(orderItem.get('payCount'))
        verticalSendContributionValues = verticalSendContributionValues + Decimal(orderItem.get('verticalSendContributionValue'))*Decimal(orderItem.get('payCount'))
        selfSendIncomesLockeds = selfSendIncomesLockeds + Decimal(orderItem.get('selfSendIncomesLocked'))*Decimal(orderItem.get('payCount'))
        verticalSendIncomes = verticalSendIncomes + Decimal(orderItem.get('verticalSendIncomes'))*Decimal(orderItem.get('payCount'))
        freePoolDays = freePoolDays + Decimal(orderItem.get('dayAward'))*Decimal(orderItem.get('payCount'))
        freePoolMonths = freePoolMonths + Decimal(orderItem.get('monthAward'))*Decimal(orderItem.get('payCount'))
        operationAwards = operationAwards + Decimal(orderItem.get('operationAward'))*Decimal(orderItem.get('payCount'))
        supplyAwards = supplyAwards + Decimal(orderItem.get('supplyAward'))*Decimal(orderItem.get('payCount'))
        helpFunds = helpFunds + Decimal(orderItem.get('helpFund'))*Decimal(orderItem.get('payCount'))
        grossProfits = grossProfits + Decimal(orderItem.get('grossProfit'))*Decimal(orderItem.get('payCount'))
    else:
        sellingPrice = _order.sellingPrice
        for orderItem in content.get('orderItemList'):
            sendContributionValues = sendContributionValues + Decimal(orderItem.get('sendContributionValue'))*Decimal(orderItem.get('payCount'))
            verticalSendContributionValues = verticalSendContributionValues + Decimal(orderItem.get('verticalSendContributionValue'))*Decimal(orderItem.get('payCount'))
            selfSendIncomesLockeds = selfSendIncomesLockeds + Decimal(orderItem.get('selfSendIncomesLocked'))*Decimal(orderItem.get('payCount'))
            verticalSendIncomes = verticalSendIncomes + Decimal(orderItem.get('verticalSendIncomes'))*Decimal(orderItem.get('payCount'))

            if orderItem.get('shopSendContributionValue'):
                shopSendContributionValueData[orderItem.get('shop')] = Decimal(shopSendContributionValueData.get(orderItem.get('shop')) or 0) + Decimal(orderItem.get('shopSendContributionValue'))*Decimal(orderItem.get('payCount'))
            if orderItem.get('shopSendIncomesLocked'):
                shopSendIncomesLockedData[orderItem.get('shop')] = Decimal(shopSendIncomesLockedData.get(orderItem.get('shop')) or 0) + Decimal(orderItem.get('shopSendIncomesLocked'))*Decimal(orderItem.get('payCount'))
            if orderItem.get('shop_balance'):
                shop_balanceData[orderItem.get('shop')] = Decimal(shop_balanceData.get(orderItem.get('shop')) or 0) + Decimal(orderItem.get('shop_balance'))*Decimal(orderItem.get('payCount'))
            if orderItem.get('shopParentAward'):
                shopParentAwardData[orderItem.get('shop')] = Decimal(shopParentAwardData.get(orderItem.get('shop')) or 0) + Decimal(orderItem.get('shopParentAward'))*Decimal(orderItem.get('payCount'))
            freePoolDays = freePoolDays + Decimal(orderItem.get('dayAward'))*Decimal(orderItem.get('payCount'))
            freePoolMonths = freePoolMonths + Decimal(orderItem.get('monthAward'))*Decimal(orderItem.get('payCount'))
            operationAwards = operationAwards + Decimal(orderItem.get('operationAward'))*Decimal(orderItem.get('payCount'))
            supplyAwards = supplyAwards + Decimal(orderItem.get('supplyAward') or 0)*Decimal(orderItem.get('payCount'))
            helpFunds = helpFunds + Decimal(orderItem.get('helpFund'))*Decimal(orderItem.get('payCount'))
            grossProfits = grossProfits + Decimal(orderItem.get('grossProfit'))*Decimal(orderItem.get('payCount'))

    # 赠送贡献点
    if sendContributionValues>0:
        payway = 'contributionValue'
        UserDao().addWallet(payway, _order.user, sendContributionValues)
        data = {}
        data['scene'] = 'sendForExpense'
        data['user'] = _order.user.id
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = sendContributionValues
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

    # 赠送上级贡献点
    if verticalSendContributionValues > 0:
        payway = 'contributionValue'
        if _order.user.parent:
            UserDao().addWallet(payway, _order.user.parent, verticalSendContributionValues)
            data = {}
            data['scene'] = 'verticalAward'
            data['user'] = _order.user.parent.id
            data['fromUser'] = _order.user.id
            data['orderId'] = _order.orderId
            data['money'] = verticalSendContributionValues
            data['payway'] = payway
            data['changeWay'] = 'add'
            data['orderStatus'] = 'FINISH'
            RecordIncomesDao().create(data)
    
    # 赠送商家贡献点
    payway = 'contributionValue'
    for key in shopSendContributionValueData:
        shop = ShopDao().findOneByObjId(key)
        shopUserId = shop.user.id
        shopUser = UserDao().findOneByObjId(shopUserId)
        shopSendContributionValues = Decimal(shopSendContributionValueData.get(key)).quantize(Decimal('0.00'))
        if shopSendContributionValues<=0:
            continue
        UserDao().addWallet(payway, shopUser, shopSendContributionValues)
        data = {}
        data['scene'] = 'sendForExpense'
        data['shop'] = shop.id
        data['user'] = shopUserId
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = shopSendContributionValues
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

    # 赠送锁定积分
    # 只有当都是礼包专区的商品，且总订单金额大于10000送3倍
    flag = True
    for orderItem in content.get('orderItemList'):
        item = ItemDao().findOneByObjId(orderItem.get('item'))
        if not item.activity or item.activity.key != 'giftpacks':
            flag = False
            break
    if sellingPrice >= Decimal(10000) and flag:
        selfSendIncomesLockeds = sellingPrice * Decimal(3)
    if selfSendIncomesLockeds>0:
        payway = 'incomesLocked'
        UserDao().addWallet(payway, _order.user, selfSendIncomesLockeds)
        data = {}
        data['scene'] = 'sendForExpense'
        data['user'] = _order.user.id
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = selfSendIncomesLockeds
        data['moneyLocked'] = selfSendIncomesLockeds
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

    # 赠送原积分转换为锁定积分
    if _order.user.incomesOriginal > 0:
        selfSendIncomesLockedsForOriginal = 0
        if _order.user.incomesOriginal < selfSendIncomesLockeds:
            selfSendIncomesLockedsForOriginal = _order.user.incomesOriginal
        else:
            selfSendIncomesLockedsForOriginal = selfSendIncomesLockeds
        # 减少原积分
        if selfSendIncomesLockedsForOriginal>0:
            payway = 'incomesOriginal'
            UserDao().subWallet(payway, _order.user, selfSendIncomesLockedsForOriginal)
            data = {}
            data['scene'] = 'fromOriginal'
            data['user'] = _order.user.id
            data['fromUser'] = _order.user.id
            data['orderId'] = _order.orderId
            data['money'] = selfSendIncomesLockedsForOriginal
            data['payway'] = payway
            data['changeWay'] = 'sub'
            data['orderStatus'] = 'FINISH'
            RecordIncomesDao().create(data)

            payway = 'incomesLocked'
            UserDao().addWallet(payway, _order.user, selfSendIncomesLockedsForOriginal)
            data = {}
            data['scene'] = 'fromOriginal'
            data['user'] = _order.user.id
            data['fromUser'] = _order.user.id
            data['orderId'] = _order.orderId
            data['money'] = selfSendIncomesLockedsForOriginal
            data['moneyLocked'] = selfSendIncomesLockedsForOriginal
            data['payway'] = payway
            data['changeWay'] = 'add'
            data['orderStatus'] = 'FINISH'
            RecordIncomesDao().create(data)
    
    # 赠送商户锁定积分
    payway = 'incomesLocked'
    for key in shopSendIncomesLockedData:
        shop = ShopDao().findOneByObjId(key)
        shopUserId = shop.user.id
        shopUser = UserDao().findOneByObjId(shopUserId)
        shopSendIncomesLockeds = Decimal(shopSendIncomesLockedData.get(key)).quantize(Decimal('0.00'))
        if shopSendIncomesLockeds<=0:
            continue
        UserDao().addWallet(payway, shopUser, shopSendIncomesLockeds)
        data = {}
        data['scene'] = 'sendForExpense'
        data['shop'] = shop.id
        data['user'] = shopUserId
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = shopSendIncomesLockeds
        data['moneyLocked'] = shopSendIncomesLockeds
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

    # 赠送上级购物积分
    if verticalSendIncomes>0:
        payway = 'incomes'
        if _order.user.parent:
            UserDao().addWallet(payway, _order.user.parent, verticalSendIncomes)
            data = {}
            data['scene'] = 'verticalAward'
            data['user'] = _order.user.parent.id
            data['fromUser'] = _order.user.id
            data['orderId'] = _order.orderId
            data['money'] = verticalSendIncomes
            data['payway'] = payway
            data['changeWay'] = 'add'
            data['orderStatus'] = 'FINISH'
            RecordIncomesDao().create(data)

    # 商户推荐人奖励
    payway = 'incomes'
    for key in shopParentAwardData:
        shop = ShopDao().findOneByObjId(key)
        shopParent = shop.user.parent
        if not shopParent:
            continue
        shopParentAwards = Decimal(shopParentAwardData.get(key)).quantize(Decimal('0.00'))
        if shopParentAwards<=0:
            continue
        UserDao().addWallet(payway, shopParent, shopParentAwards)
        data = {}
        data['scene'] = 'verticalShopAward'
        data['user'] = shopParent.id
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = shopParentAwards
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

    # 日释放池
    if freePoolDays>0:
        payway = 'freePoolDay'
        LesseeDao().addWallet(payway, freePoolDays)
        data = {}
        data['scene'] = 'sendForExpense'
        data['user'] = ''
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = freePoolDays
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
    # 月释放池
    if freePoolMonths>0:
        payway = 'freePoolMonth'
        LesseeDao().addWallet(payway, freePoolMonths)
        data = {}
        data['scene'] = 'sendForExpense'
        data['user'] = ''
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = freePoolMonths
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
    # 运营补贴池
    if operationAwards>0:
        payway = 'operationAwardPool'
        LesseeDao().addWallet(payway, operationAwards)
        data = {}
        data['scene'] = 'sendForExpense'
        data['user'] = ''
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = operationAwards
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
    # 创业基金池
    if helpFunds>0:
        payway = 'helpFundPool'
        LesseeDao().addWallet(payway, helpFunds)
        data = {}
        data['scene'] = 'sendForExpense'
        data['user'] = ''
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = helpFunds
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
    # 供应链奖励
    if supplyAwards>0:
        payway = 'supplyAwards'
        if supplyAwards>0:
            LesseeDao().addWallet(payway, supplyAwards)
            data = {}
            data['scene'] = 'sendForExpense'
            data['user'] = ''
            data['fromUser'] = _order.user.id
            data['orderId'] = _order.orderId
            data['money'] = supplyAwards
            data['payway'] = payway
            data['changeWay'] = 'add'
            data['orderStatus'] = 'FINISH'
            RecordIncomesDao().create(data)
    # 毛利润
    if grossProfits>0:
        payway = 'grossProfit'
        LesseeDao().addWallet(payway, grossProfits)
        data = {}
        data['scene'] = 'sendForExpense'
        data['user'] = ''
        data['fromUser'] = _order.user.id
        data['orderId'] = _order.orderId
        data['money'] = grossProfits
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

    return sendContributionValues